import axios from 'axios';
import { log } from '../utils/log';
import fs from 'node:fs';
import { resolve } from 'node:path';

/**
 * 打包选项
 */
export interface Options {
  /**
   * 源码位置，必填项
   */
  srcDir?: './dist' | string;
  /**
   * NW runtime version
   */
  version?: 'latest' | 'stable' | 'lts' | string;
  /**
   * NW runtime build flavor
   */
  flavor?: 'normal' | 'sdk';
  /**
   * NW supported platforms
   */
  platform?: 'win' | 'osx' | 'linux';
  /**
   * NW supported architectures
   */
  arch?: 'x64' | 'arm64' | 'ia32';
  /**
   * Directory to store build artifacts
   */
  outDir?: string;
  /**
   * Directory to store NW binaries
   */
  cacheDir?: string;
  /**
   * Output log level
   */
  logLevel?: 'info' | 'debug';
  /**
   * URI to download NW binaries from
   */
  downloadUrl?: string;
  /**
   * 运行模式
   */
  mode?: 'build' | 'run' | 'get';
}

export function resolverOptions(options: Options) {
  options.srcDir = options.srcDir ?? './dist';
  options.version = options.version ?? 'latest';
  options.platform = options.platform ?? 'win';
  options.arch = options.arch ?? 'x64';
  options.downloadUrl = options.downloadUrl ?? 'https://npmmirror.com/mirrors/nwjs';
  options.cacheDir = options.cacheDir ?? './cache';
  options.outDir = options.outDir ?? './out';
  options.logLevel = options.logLevel ?? 'info';
  options.mode = options.mode ?? 'build';
  if ('run' === options.mode) {
    options.flavor = options.flavor ?? 'sdk';
  } else {
    options.flavor = options.flavor ?? 'normal';
  }
  return options;
}

export async function parseVersion(options: Options) {
  createCacheFolder(options);
  if ('latest' !== options.version && 'stable' !== options.version && 'lts' !== options.version) return;
  log.debug(`版本号是: ${options.version}，即将解析版本`);
  let manifestPath = resolve(`${options.cacheDir}/manifest.json`);
  if (!fs.existsSync(manifestPath)) {
    log.debug(`版本文件: '${manifestPath}' 不存在，即将从官网下载`);
    let res = await axios.get(`https://nwjs.io/versions`, {responseType: 'arraybuffer'});
    let data = res.data;
    let buffer = Buffer.from(data);
    createCacheFolder(options);
    fs.writeFileSync(manifestPath, buffer, {encoding: 'utf-8'});
    log.debug(`版本文件下载成功`);
  }
  let manifestJson = fs.readFileSync(manifestPath, {encoding: 'utf-8'});
  let manifest = JSON.parse(manifestJson);
  options.version = manifest[options.version].match(`v(.*)`)[1];
  log.debug(`版本号解析成功，值为:${options.version}`);
}

export function createCacheFolder(options: Options) {
  if (!fs.existsSync(options.cacheDir ?? './cache')) {
    let cacheDir = resolve(options.cacheDir ?? './cache');
    log.debug(`本地缓存目录不存在，即将创建: '${cacheDir}'`);
    fs.mkdirSync(cacheDir);
    log.debug('本地缓存目录创建成功');
  }
}
